<template>
  <div v-if="partsType.length > 0">
    <client-only>
      <van-row>
        <van-col span="6">
          <van-sidebar v-model="activeKey" @change="onChange">
            <van-sidebar-item
              v-for="pt in partsType"
              :key="pt.id"
              :title="pt.name"
            />
            <div :style="popup_blank_box_style"></div>
          </van-sidebar>
        </van-col>
        <van-col span="18" class="search">
          <van-search
            v-model="value"
            placeholder="请输入搜索关键词"
            class="search-bar"
            :clearable="false"
            @input="onInput"
          />
          <van-list v-model="loading" :finished="finished" @load="onLoad">
            <n-link
              v-for="(pl, i) in partsList"
              :key="'part_' + i"
              :to="'/parts-detail?id=' + pl.id"
              ><van-card :desc="pl.name" :thumb="pl.img"
            /></n-link>
            <InFeedAdsense
              data-ad-layout-key="-gw-3+1f-3d+2z"
              data-ad-client="ca-pub-6243451787655828"
              data-ad-slot="8442301843"
            >
            </InFeedAdsense>
            <div v-if="finished" style="padding-bottom: 40px">
              <p style="font-size: 12px; text-align: center; color: grey">
                到底了👻如果找不到想要的零件👇
              </p>
              <van-button
                color="#f60"
                url="https://www.17fpv.com/723.html"
                style="margin: auto; display: block"
                size="small"
                >向小哥反馈</van-button
              >
            </div>
          </van-list>

          <div :style="popup_blank_box_style"></div>
        </van-col>
      </van-row>
      <div style="position: fixed; right: 0; bottom: 100px"></div>
    </client-only>
  </div>
</template>

<script>
export default {
  name: 'PartsList',
  components: {},
  props: {},
  async asyncData(context) {
    // console.log(context)

    // context代表上下文
    // var finished = false
    // var partsList = []
    var partsType = []

    // await context.$axios
    //   .get('https://www.17fpv.com/wp-json/jiangqie/v1/part/list',
    //     {
    //       params:
    //         {
    //           start: 0,
    //           type: 1,
    //           name: '机架'
    //         }
    //     })
    //   .then(response =>
    //   {
    //     if (response.data.data.length < 12)
    //     {
    //       finished = true
    //     }
    //     partsList = response.data.data
    //   })
    //   .catch(function(error)
    //   {
    //     console.log(error)
    //   });

    //获取所有分类
    await context.$axios
      .get('https://www.17fpv.com/wp-json/jiangqie/v1/part/alltype')
      .then((response) => {
        partsType = response.data.data.parts_type
      })
      .catch(function (error) {
        // 请求失败处理
        console.log(error)
      })
    return {
      // partsList: partsList,
      // finished: finished,
      // current_start: 1,
      partsType: partsType,
    }
  },
  data() {
    return {
      activeKey: 0,
      value: '',
      loading: false,
      finished: false,
      refreshing: false,
      partsType: [],
      partsList: [],
      choosePartList: [],

      current_start: 0,
      current_type: 1,
      current_partName: '机架',
      cancelRequest: null,
      popup_blank_box_style: '', //popup补位box高度
    }
  },
  head() {
    return {
      title: '穿越机助手|配置清单|穿越机教程 - 一起FPV',
      meta: [
        {
          hid: this.title,
          name: this.title,
          content: this.title,
        },
        {
          itemprop: 'title',
          name: 'title',
          content: this.title,
        },
        {
          itemprop: 'description',
          name: 'description',
          content: this.title,
        },
        {
          itemprop: 'url',
          name: 'url',
          content: 'http://app.17fpv.com/parts-list',
        },
        {
          itemprop: 'image',
          name: 'image',
          content: '/favicon.ico',
        },
      ],
    }
  },
  mounted() {
    // let toast = this.$toast.loading({
    //   message: '加载中...',
    //   forbidClick: true,
    //   duration: 0
    // });
    // //加载默认数据
    // this.$axios
    //   .get('https://www.17fpv.com/wp-json/jiangqie/v1/part/alltype')
    //   .then(response => {
    //     this.partsType = response.data.data.parts_type
    //     toast.clear()
    //   })
    //   .catch(function(error)
    //   { // 请求失败处理
    //     console.log(error);
    //   });
  },

  methods: {
    onLoad() {
      //此方法来源有几种：1，正常下拉加载 2，切换tab栏 3，搜索关键词
      //1，正常下拉加载(需要等到之前所有的内容加载完毕之后才能继续加载)
      //2，切换tab栏目（直接清除之前的axios请求，加载新内容）
      //3，搜索关键词（直接清除之前的axios请求，加载新内容）

      //判断逻辑：如果current_start >= 1，则认为是正常下拉加载
      if (this.current_start >= 1) {
        // console.log(this.current_start)
        // if (this.loading) {
        //   return
        // }
      }
      // 如果current_start = 0，则认为是需要撤销之前的请求
      if (this.current_start == 0) {
        // 2. 准备执行新的请求前，先将前一个请求取消
        // 如果前一个请求执行完了，执行取消请求不会有其他操作
        if (typeof this.cancelRequest === 'function') {
          this.cancelRequest('请求太频繁了，请稍后再试～')
        }
      }

      var CancelToken = this.$axios.CancelToken

      let that = this
      this.$axios
        .get('https://www.17fpv.com/wp-json/jiangqie/v1/part/list', {
          params: {
            start: this.current_start,
            type: this.current_type,
            name: this.value,
          },
          cancelToken: new CancelToken(function executor(c) {
            // 1. cancel函数赋值给cancelRequest属性
            // 从而可以通过cancelRequest执行取消请求的操作
            that.cancelRequest = c
          }),
        })
        .then((response) => {
          if (response.data.data.length < 12) {
            this.finished = true
          }
          this.partsList = this.partsList.concat(response.data.data)
          this.loading = false

          this.current_start += 1
        })
        .catch(function (error) {
          if (that.$axios.isCancel(error)) {
            console.log('Request canceled', error.message)
          } else {
            console.log(error)
          }
        })
    },
    onRefresh() {
      // 清空列表数据
      this.finished = false

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    },
    onChange(index) {
      this.current_type = this.partsType[index].id
      this.current_partName = this.partsType[index].name
      this.current_start = 0

      this.loading = false
      this.finished = false
      this.refreshing = false

      //     清空列表数据
      this.partsList = []

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    },
    onInput() {
      this.current_start = 0

      this.loading = false
      this.finished = false
      this.refreshing = false

      //     清空列表数据
      this.partsList = []

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    },
    detail(id) {
      window.open('https://www.17fpv.com/category/parts/info?id=' + id)
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.van-sidebar::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 2px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}

.van-sidebar::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px grey;
  background: white;
}

.van-sidebar::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px white;
  border-radius: 10px;
  background: white;
}

.search::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 2px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}

.search::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px grey;
  background: white;
}

.search::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px white;
  border-radius: 10px;
  background: white;
}

.left-box {
  width: 25%;
  /* height: 1%; */
  overflow: auto;
  /* position: fixed; */
  left: 0;
  top: 0;
}

.right-box {
  width: 75%;
  height: 90%;
  overflow: auto;
  position: fixed;
  right: 0;
  top: 0;
}

.van-sidebar {
  width: 100%;
  text-align: center;
  height: 100%;
  position: fixed;
  left: 0;
  /* top: 0; */
  width: 25%;
}

.search {
  position: fixed;
  right: 0;
  overflow: auto;
  height: 100%;
}

.search-bar {
  position: fixed;
  /* top: 0; */
  right: 0;
  width: 75%;
  z-index: 2000;
  padding: 12px 7px;
  /* margin-top: -1px; */
  box-shadow: 10px 0px 10px grey;
}

.van-sidebar-item {
  padding: 15px 2px;
}

.van-list {
  padding-top: 60px;
}

.van-card {
  padding: 5px 5px;
  border-bottom: 1px solid #f6f6f6;
  background-color: white;
}

.van-card__content {
  min-height: 70px;
}

.van-card__desc {
  max-height: 60px;
  text-align: left;
}

.van-card__thumb {
  width: 60px;
  height: 60px;
}

.van-card__thumb img {
  border-radius: 3px;
}

.van-ellipsis {
  white-space: break-spaces;
}

.goods-card {
  margin: 0;
  background-color: white;
}

.delete-button {
  height: 100%;
}

.van-swipe-cell {
  margin-top: 5px;
}

.van-tag--danger {
  margin-top: 5px;
}

.van-uploader {
  padding: 15px;
}

.van-sidebar-item--select::before {
  height: 50px;
}
.van-cell__value--alone {
  font-size: 16px;
}
.van-field {
  font-size: 16px;
}
.van-dialog {
  border-radius: 5px;
}
</style>
